﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;
using RestSharp;

namespace ComicIsland.App.Controls
{
    public partial class QQAuthenticationPage : PhoneApplicationPage
    {
        private string scope = "get_user_info,upload_pic,add_t,add_pic_t,get_info";
        private UserThirdLoginInfo QQUserInfo = new UserThirdLoginInfo();
        public QQAuthenticationPage()
        {
            InitializeComponent();
            //
            QQUserInfo.ThirdPlatform = (int)Helper.ThirdPlatform.QQ;
            QQUserInfo.InsertDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //
            InitUserLoginPage();
        }

        void InitUserLoginPage()
        {
            string requestUrl = string.Format("https://graph.qq.com/oauth2.0/authorize?display=mobile&response_type=code&client_id={0}&client_secret={1}&redirect_uri={2}&state={3}&scope={4}",
                App.QQ_AppKey, App.QQ_AppSecret, Uri.EscapeDataString(App.QQ_RedirectUri), App.QQ_StateKey, scope);

            this.webBrowser.Navigate(new Uri(requestUrl, UriKind.Absolute));
        }

        private void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.ToString().StartsWith(App.QQ_RedirectUri) && e.Uri.ToString().Contains("code=") && e.Uri.ToString().Contains("state=" + App.QQ_StateKey))//http://www.manhuadao.cn/?code=076E1C5A114CFF38713A5EEA1BCAEDF2&state=ComicIsland
            {
                this.psbProgress.Visibility = System.Windows.Visibility.Visible;
                this.webBrowser.Visibility = System.Windows.Visibility.Collapsed;
                //获取AccessToken请求的code                
                Dictionary<string, string> keyValues = Helper.GetQueryString(e.Uri.Query);
                string code = keyValues["code"];
                GetAccessToken(code);
            }
            else
            {
                LogHelper.LogInfo(e.Uri.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        private void webBrowser_Navigated(object sender, NavigationEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
           {
               this.psbProgress.Visibility = System.Windows.Visibility.Collapsed;
           });
        }

        private void webBrowser_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                if (this.webBrowser.Visibility == System.Windows.Visibility.Visible)
                {
                    this.psbProgress.Visibility = System.Windows.Visibility.Collapsed;
                    MessageToastManager.Show("请求数据出错！");
                }
            });
        }


        private void GetAccessToken(string code)
        {
            string requestUrl = string.Format("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri={3}", code, App.QQ_AppKey, App.QQ_AppSecret, Uri.EscapeDataString(App.QQ_RedirectUri));
            var client = new RestClient(requestUrl);
            var rest = new RestRequest(Method.GET);
            client.ExecuteAsync(rest, (response) =>
            {
                //access_token=0D4B86A9DE2FECB09CC3CD647F52923D&expires_in=7776000&refresh_token=9EE1DB8BEA8BDE2DEB761715356B9470
                LogHelper.LogInfo(response.Content, this.GetType(), MethodBase.GetCurrentMethod());
                if (response.ErrorException == null && response.StatusCode == HttpStatusCode.OK)
                {
                    //获取AccessToken
                    Dictionary<string, string> keyValues = Helper.GetQueryString(response.Content);
                    string accessToken = keyValues["access_token"];
                    QQUserInfo.RefleshToken = keyValues["refresh_token"];
                    QQUserInfo.ExpriesIn = keyValues["expires_in"];
                    ////获取OpenId
                    this.GetOpenId(accessToken);
                }
                else
                {
                    MessageToastManager.Show("登录失败！");
                }
            });
        }

        void GetOpenId(string accessToken)
        {
            string requestUrl = string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", accessToken);
            var client = new RestClient(requestUrl);
            var rest = new RestRequest(Method.GET);
            client.ExecuteAsync(rest, (response) =>
            {
                LogHelper.LogInfo(response.Content, this.GetType(), MethodBase.GetCurrentMethod());
                //callback( {"client_id":"204134","openid":"11123A039593134E4CFD4DE719A1A78D"} );
                if (response.ErrorException == null && response.StatusCode == HttpStatusCode.OK)
                {
                    string openId = ParseOpenId(response.Content);
                    this.GetUserInfo(accessToken, openId);
                }
                else
                {
                    MessageToastManager.Show("登录失败！");
                }
            });
        }

        void GetUserInfo(string accessToken, string openId)
        {
            string requestUrlUserInfo = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", accessToken, App.QQ_AppKey, openId);
            var client = new RestClient(requestUrlUserInfo);
            var rest = new RestRequest(Method.GET);
            client.ExecuteAsync(rest, (response) =>
            {
                LogHelper.LogInfo(response.Content, this.GetType(), MethodBase.GetCurrentMethod());
                if (response.ErrorException == null && response.StatusCode == HttpStatusCode.OK)
                {
                    JObject jo = JObject.Parse(response.Content);
                    try
                    {
                        JToken screen_name = jo["nickname"];
                        JToken gender = jo["gender"];
                        JToken profile_image_url = jo["figureurl_qq_2"];
                        //                        
                        QQUserInfo.AccessToken = accessToken;
                        QQUserInfo.UserId = openId;
                        QQUserInfo.ScreenName = screen_name.ToString();
                        if (!string.IsNullOrWhiteSpace(gender.ToString()) && gender.ToString().ToLower().Equals("男"))
                            QQUserInfo.Gender = ((int)Helper.UserGender.Male).ToString();
                        else
                            QQUserInfo.Gender = ((int)ComicIsland.Common.Helper.UserGender.Female).ToString();
                        QQUserInfo.ProfileImageUrl = profile_image_url.ToString();
                    }
                    catch { }
                    finally
                    {
                        if (string.IsNullOrWhiteSpace(QQUserInfo.AccessToken) || string.IsNullOrWhiteSpace(QQUserInfo.UserId)
                      || string.IsNullOrWhiteSpace(QQUserInfo.ExpriesIn) || string.IsNullOrWhiteSpace(QQUserInfo.ScreenName) || string.IsNullOrWhiteSpace(QQUserInfo.ProfileImageUrl))
                        {
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                MessageToastManager.Show("登录失败，请重试！", MessageToastLevel.Error);
                                if ((Application.Current.RootVisual as PhoneApplicationFrame).CanGoBack)
                                {
                                    (Application.Current.RootVisual as PhoneApplicationFrame).GoBack();
                                }
                            });
                        }
                        else
                        {
                            Login(QQUserInfo, this.psbProgress);
                        }
                    }
                }
                else
                {
                    MessageToastManager.Show("登录失败！");
                }
            });
        }



        private string ParseOpenId(string callback)
        {
            string key = "\"openid\":\"";
            int startIndex = callback.IndexOf(key);
            int endIndex = callback.IndexOf("\"", startIndex + key.Length);
            string openId = string.Empty;
            openId = callback.Substring(startIndex + key.Length, endIndex - startIndex - key.Length);
            return openId;
        }



        public static void Login(UserThirdLoginInfo userLoginInfo, ProgressStatusBar progressStatusBar = null)
        {
            #region 绑定数据并登录
            //{"uid":"1872997893","platform":"2","islogout":"0","gender":"1","logininfo":"","screen_name":"国学经典食疗养生楚才书店","lastloginsystemversion":"4.2.1","lastlogindevicename":"GFIVE","profile_image_url":"http:\%2F\%2Ftp2.sinaimg.cn\%2F1872997893\%2F180\%2F40019484811\%2F1","access_token":"2.008_ukCC0eYD6W06e1013bbbZfgajD"}
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/userlogin");//, "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, typeof(QQAuthenticationPage), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("uid", userLoginInfo.UserId);
            parameters.Add("platform", userLoginInfo.ThirdPlatform.ToString());
            parameters.Add("islogout", ((int)Helper.UserLoginType.Login).ToString());
            parameters.Add("gender", userLoginInfo.Gender);
            parameters.Add("screen_name", Helper.UriEscapeDataString(userLoginInfo.ScreenName));
            parameters.Add("profile_image_url", userLoginInfo.ProfileImageUrl);
            parameters.Add("access_token", userLoginInfo.AccessToken);
            parameters.Add("lastlogindevicename", Helper.UriEscapeDataString(DeviceStatus.DeviceName));
            parameters.Add("lastloginsystemversion", Variables.GetVersion());
            //parameters.Add("logininfo", Helper.UriEscapeDataString(userInfo.DetailInfo));
            parameters.Add("logininfo", "");

            PostClientHelper proxy = new PostClientHelper(parameters);
            LogHelper.LogInfo(proxy.PostData.ToString(), typeof(QQAuthenticationPage), MethodBase.GetCurrentMethod());
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (progressStatusBar != null)
                            progressStatusBar.Visibility = System.Windows.Visibility.Collapsed;
                    });

                    if (e.Error != null)
                    {
                        LogHelper.LogError(e.Error.ToString(), typeof(QQAuthenticationPage), MethodBase.GetCurrentMethod());
                        return;
                    }

                    #region 获取结果处理
                    string result = e.Result;

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        LogHelper.LogError("Result is empty.");
                        //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        LogHelper.LogError(result);
                        //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                        return;
                    }

                    LogHelper.LogInfo(result, typeof(QQAuthenticationPage), MethodBase.GetCurrentMethod());
                    //
                    var rootCharacterString = JSONHelper.Deserialize<JsonComicUserLogin>(result);
                    if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null))
                    {
                        //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                    }
                    else
                    {
                        var item = rootCharacterString.Info;
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            if (item != null)
                            {
                                userLoginInfo.ComicUserId = item.Id;
                                string json = JSONHelper.Serialize<UserThirdLoginInfo>(userLoginInfo);
                                IsolatedStorageHelper.Instance.WriteText(json, KEYS.KEY_UserThirdLoginInfo, true);
                            }
                            else
                            {
                                MessageToastManager.Show("登录失败，请重试！", MessageToastLevel.Error);
                            }
                            if ((Application.Current.RootVisual as PhoneApplicationFrame).CanGoBack)
                            {
                                (Application.Current.RootVisual as PhoneApplicationFrame).GoBack();
                            }
                        });
                    }
                    #endregion 获取结果处理
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.ToString(), typeof(QQAuthenticationPage), MethodBase.GetCurrentMethod());
                }
                finally
                {

                }
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
            #endregion 绑定数据并登录
        }
    }
}